package com.ckzp.core.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by 51594 on 2022/7/27.
 */
public class CookieUtil {

    /**
     * \
     *
     * @param response
     * @param cookieName
     * @param value
     */
    public static void setCookie(HttpServletResponse response, String cookieName, String value) {
        Cookie cookie = new Cookie(cookieName, value);
        //cookie.setMaxAge(1 * 24 * 60 * 60);
        cookie.setMaxAge(Integer.MAX_VALUE);
        cookie.setPath("/");
        response.addCookie(cookie);
    }


    /**
     * \
     *
     * @param response
     * @param cookieName
     */
    public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
        Cookie cookies[] = request.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie sCookie = cookies[i];
                String sname = sCookie.getName();
                if (sname.equals(cookieName)) {
                    sCookie.setMaxAge(0);
                    sCookie.setPath("/");
                    response.addCookie(sCookie);
                }
            }
        }
    }

    /**
     * @param request
     * @param cookieName
     * @return
     */
    public static String getCookie(HttpServletRequest request, String cookieName) {
        Cookie cookies[] = request.getCookies();
        Cookie sCookie = null;
        String value = "";
        String svalue = null;
        String sname = null;
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                sCookie = cookies[i];
                svalue = sCookie.getValue();
                sname = sCookie.getName();
//            System.out.println("sCookie" + sname);
                if (sname.equals(cookieName)) {
                    value = svalue;
                }
            }
        }
        return value;
    }
}
